<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=2">
<meta name="theme-color" content="#222">
<meta name="generator" content="Hexo 5.3.0">


  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png">
  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon-32x32-next.png">
  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon-16x16-next.png">
  <link rel="mask-icon" href="/images/logo.svg" color="#222">

<link rel="stylesheet" href="/css/main.css">



<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@fortawesome/fontawesome-free@5.15.3/css/all.min.css">
  <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/animate.css@3.1.1/animate.min.css">

<script class="hexo-configurations">
    var NexT = window.NexT || {};
    var CONFIG = {"hostname":"example.com","root":"/","images":"/images","scheme":"Muse","version":"8.3.0","exturl":false,"sidebar":{"position":"left","display":"post","padding":18,"offset":12},"copycode":false,"bookmark":{"enable":false,"color":"#222","save":"auto"},"fancybox":false,"mediumzoom":false,"lazyload":false,"pangu":false,"comments":{"style":"tabs","active":null,"storage":true,"lazyload":false,"nav":null},"motion":{"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"fadeInDown","post_body":"fadeInDown","coll_header":"fadeInLeft","sidebar":"fadeInUp"}},"prism":false,"i18n":{"placeholder":"Searching...","empty":"We didn't find any results for the search: ${query}","hits_time":"${hits} results found in ${time} ms","hits":"${hits} results found"}};
  </script>
<meta name="description" content="1. 默认绑定默认绑定就是其他绑定都无法应用的时候就是默认绑定 function foo()&amp;#123;    var a &#x3D; 3;	console.log(this.a);&amp;#125;var a &#x3D; 2;foo(); &#x2F;&#x2F;2console.log(a) &#x2F;&#x2F;2 函数调用了this的默认绑定，因此this指向全局对象，但是如果再严格模式中，this会指向undefined this只和调用位置有关">
<meta property="og:type" content="article">
<meta property="og:title" content="this指向详解">
<meta property="og:url" content="http://example.com/2021/04/05/JS%20U%20DONT%20KNOW%201/this%E6%8C%87%E5%90%91%E8%AF%A6%E8%A7%A3/index.html">
<meta property="og:site_name" content="Lawted&#39;s Blog">
<meta property="og:description" content="1. 默认绑定默认绑定就是其他绑定都无法应用的时候就是默认绑定 function foo()&amp;#123;    var a &#x3D; 3;	console.log(this.a);&amp;#125;var a &#x3D; 2;foo(); &#x2F;&#x2F;2console.log(a) &#x2F;&#x2F;2 函数调用了this的默认绑定，因此this指向全局对象，但是如果再严格模式中，this会指向undefined this只和调用位置有关">
<meta property="og:locale" content="en_US">
<meta property="article:published_time" content="2021-04-05T13:00:56.000Z">
<meta property="article:modified_time" content="2021-05-07T01:31:31.165Z">
<meta property="article:author" content="Lawted Wu">
<meta property="article:tag" content="JS U dont know 1">
<meta name="twitter:card" content="summary">


<link rel="canonical" href="http://example.com/2021/04/05/JS%20U%20DONT%20KNOW%201/this%E6%8C%87%E5%90%91%E8%AF%A6%E8%A7%A3/">


<script class="page-configurations">
  // https://hexo.io/docs/variables.html
  CONFIG.page = {
    sidebar: "",
    isHome : false,
    isPost : true,
    lang   : 'en'
  };
</script>
<title>this指向详解 | Lawted's Blog</title>
  




  <noscript>
  <style>
  body { margin-top: 2rem; }

  .use-motion .menu-item,
  .use-motion .sidebar,
  .use-motion .post-block,
  .use-motion .pagination,
  .use-motion .comments,
  .use-motion .post-header,
  .use-motion .post-body,
  .use-motion .collection-header {
    visibility: visible;
  }

  .use-motion .header,
  .use-motion .site-brand-container .toggle,
  .use-motion .footer { opacity: initial; }

  .use-motion .site-title,
  .use-motion .site-subtitle,
  .use-motion .custom-logo-image {
    opacity: initial;
    top: initial;
  }

  .use-motion .logo-line {
    transform: scaleX(1);
  }

  .search-pop-overlay, .sidebar-nav { display: none; }
  .sidebar-panel { display: block; }
  </style>
</noscript>

</head>

<body itemscope itemtype="http://schema.org/WebPage" class="use-motion">
  <div class="headband"></div>

  <main class="main">
    <header class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-container">
  <div class="site-nav-toggle">
    <div class="toggle" aria-label="Toggle navigation bar" role="button">
        <span class="toggle-line"></span>
        <span class="toggle-line"></span>
        <span class="toggle-line"></span>
    </div>
  </div>

  <div class="site-meta">

    <a href="/" class="brand" rel="start">
      <i class="logo-line"></i>
      <h1 class="site-title">Lawted's Blog</h1>
      <i class="logo-line"></i>
    </a>
  </div>

  <div class="site-nav-right">
    <div class="toggle popup-trigger">
    </div>
  </div>
</div>



<nav class="site-nav">
  <ul class="main-menu menu">
        <li class="menu-item menu-item-home"><a href="/" rel="section"><i class="fa fa-home fa-fw"></i>Home</a></li>
        <li class="menu-item menu-item-tags"><a href="/tags/" rel="section"><i class="fa fa-tags fa-fw"></i>Tags</a></li>
        <li class="menu-item menu-item-archives"><a href="/archives/" rel="section"><i class="fa fa-archive fa-fw"></i>Archives</a></li>
  </ul>
</nav>




</div>
        
  
  <div class="toggle sidebar-toggle" role="button">
    <span class="toggle-line"></span>
    <span class="toggle-line"></span>
    <span class="toggle-line"></span>
  </div>

  <aside class="sidebar">

    <div class="sidebar-inner sidebar-nav-active sidebar-toc-active">
      <ul class="sidebar-nav">
        <li class="sidebar-nav-toc">
          Table of Contents
        </li>
        <li class="sidebar-nav-overview">
          Overview
        </li>
      </ul>

      <div class="sidebar-panel-container">
        <!--noindex-->
        <div class="post-toc-wrap sidebar-panel">
            <div class="post-toc animated"><ol class="nav"><li class="nav-item nav-level-2"><a class="nav-link" href="#1-%E9%BB%98%E8%AE%A4%E7%BB%91%E5%AE%9A"><span class="nav-number">1.</span> <span class="nav-text">1. 默认绑定</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#2-%E9%9A%90%E5%BC%8F%E7%BB%91%E5%AE%9A"><span class="nav-number">2.</span> <span class="nav-text">2. 隐式绑定</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#3-%E6%98%BE%E5%BC%8F%E7%BB%91%E5%AE%9A"><span class="nav-number">3.</span> <span class="nav-text">3. 显式绑定</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#1-%E7%A1%AC%E7%BB%91%E5%AE%9A"><span class="nav-number">3.1.</span> <span class="nav-text">1. 硬绑定</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#4-new%E7%BB%91%E5%AE%9A"><span class="nav-number">4.</span> <span class="nav-text">4.new绑定</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#5-%E4%BC%98%E5%85%88%E7%BA%A7"><span class="nav-number">5.</span> <span class="nav-text">5.优先级</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#6-%E5%88%A4%E6%96%ADthis"><span class="nav-number">6.</span> <span class="nav-text">6. 判断this</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#6-%E7%BB%91%E5%AE%9A%E4%BE%8B%E5%A4%96"><span class="nav-number">6.1.</span> <span class="nav-text">6. 绑定例外</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#%E8%A2%AB%E5%BF%BD%E7%95%A5%E7%9A%84this"><span class="nav-number">6.2.</span> <span class="nav-text">被忽略的this</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#%E9%97%B4%E6%8E%A5%E5%BC%95%E7%94%A8"><span class="nav-number">6.3.</span> <span class="nav-text">间接引用</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#this%E8%AF%8D%E6%B3%95-%E7%AE%AD%E5%A4%B4%E5%87%BD%E6%95%B0%E4%BD%9C%E7%94%A8%E5%9F%9F"><span class="nav-number">7.</span> <span class="nav-text">this词法(箭头函数作用域)</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#7-%E5%B0%8F%E7%BB%93"><span class="nav-number">8.</span> <span class="nav-text">7.小结</span></a></li></ol></div>
        </div>
        <!--/noindex-->

        <div class="site-overview-wrap sidebar-panel">
          <div class="site-author site-overview-item animated" itemprop="author" itemscope itemtype="http://schema.org/Person">
  <p class="site-author-name" itemprop="name">Lawted Wu</p>
  <div class="site-description" itemprop="description"></div>
</div>
<div class="site-state-wrap site-overview-item animated">
  <nav class="site-state">
      <div class="site-state-item site-state-posts">
          <a href="/archives/">
        
          <span class="site-state-item-count">67</span>
          <span class="site-state-item-name">posts</span>
        </a>
      </div>
      <div class="site-state-item site-state-tags">
            <a href="/tags/">
          
        <span class="site-state-item-count">8</span>
        <span class="site-state-item-name">tags</span></a>
      </div>
  </nav>
</div>
  <div class="links-of-author site-overview-item animated">
      <span class="links-of-author-item">
        <a href="https://github.com/LAWTED" title="GitHub → https:&#x2F;&#x2F;github.com&#x2F;LAWTED" rel="noopener" target="_blank"><i class="fab fa-github fa-fw"></i>GitHub</a>
      </span>
  </div>



        </div>
      </div>
        <div class="back-to-top animated" role="button" aria-label="Back to top">
          <i class="fa fa-arrow-up"></i>
          <span>0%</span>
        </div>
    </div>
  </aside>
  <div class="sidebar-dimmer"></div>


    </header>

    
  <div class="reading-progress-bar"></div>

<noscript>
  <div class="noscript-warning">Theme NexT works best with JavaScript enabled</div>
</noscript>


    <div class="main-inner post posts-expand">


  


<div class="post-block">
  
  

  <article itemscope itemtype="http://schema.org/Article" class="post-content" lang="en">
    <link itemprop="mainEntityOfPage" href="http://example.com/2021/04/05/JS%20U%20DONT%20KNOW%201/this%E6%8C%87%E5%90%91%E8%AF%A6%E8%A7%A3/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="image" content="/images/avatar.gif">
      <meta itemprop="name" content="Lawted Wu">
      <meta itemprop="description" content="">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="Lawted's Blog">
    </span>
      <header class="post-header">
        <h1 class="post-title" itemprop="name headline">
          this指向详解
        </h1>

        <div class="post-meta-container">
          <div class="post-meta">
    <span class="post-meta-item">
      <span class="post-meta-item-icon">
        <i class="far fa-calendar"></i>
      </span>
      <span class="post-meta-item-text">Posted on</span>

      <time title="Created: 2021-04-05 21:00:56" itemprop="dateCreated datePublished" datetime="2021-04-05T21:00:56+08:00">2021-04-05</time>
    </span>
      <span class="post-meta-item">
        <span class="post-meta-item-icon">
          <i class="far fa-calendar-check"></i>
        </span>
        <span class="post-meta-item-text">Edited on</span>
        <time title="Modified: 2021-05-07 09:31:31" itemprop="dateModified" datetime="2021-05-07T09:31:31+08:00">2021-05-07</time>
      </span>

  
    <span class="post-meta-item" title="Views" id="busuanzi_container_page_pv" style="display: none;">
      <span class="post-meta-item-icon">
        <i class="far fa-eye"></i>
      </span>
      <span class="post-meta-item-text">Views: </span>
      <span id="busuanzi_value_page_pv"></span>
    </span>
</div>

        </div>
      </header>

    
    
    
    <div class="post-body" itemprop="articleBody">
        <h2 id="1-默认绑定"><a href="#1-默认绑定" class="headerlink" title="1. 默认绑定"></a>1. 默认绑定</h2><p>默认绑定就是其他绑定都无法应用的时候就是默认绑定</p>
<figure class="highlight js"><table><tr><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">foo</span>(<span class="params"></span>)</span>&#123;</span><br><span class="line">    <span class="keyword">var</span> a = <span class="number">3</span>;</span><br><span class="line">	<span class="built_in">console</span>.log(<span class="built_in">this</span>.a);</span><br><span class="line">&#125;</span><br><span class="line"><span class="keyword">var</span> a = <span class="number">2</span>;</span><br><span class="line">foo(); <span class="comment">//2</span></span><br><span class="line"><span class="built_in">console</span>.log(a) <span class="comment">//2</span></span><br></pre></td></tr></table></figure>
<p>函数调用了<code>this</code>的默认绑定，因此<code>this</code>指向全局对象，但是如果再<code>严格模式</code>中，<code>this</code>会指向<code>undefined</code></p>
<p><strong><code>this</code>只和调用位置有关，和声明位置无关，和词法作用域不一样！！！</strong></p>
<h2 id="2-隐式绑定"><a href="#2-隐式绑定" class="headerlink" title="2. 隐式绑定"></a>2. 隐式绑定</h2><p>调用位置有上下文对象，也就是被某个对象拥有或者包含</p>
<figure class="highlight js"><table><tr><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">foo</span>(<span class="params"></span>)</span>&#123;</span><br><span class="line">	<span class="built_in">console</span>.log(a);</span><br><span class="line">&#125;</span><br><span class="line"><span class="keyword">var</span> obj = &#123;</span><br><span class="line">    a:<span class="number">2</span>,</span><br><span class="line">    foo:foo</span><br><span class="line">&#125;;</span><br><span class="line">obj.foo();</span><br></pre></td></tr></table></figure>
<p>可以说<code>foo()</code>被调用的时候，<code>obj</code>包含它，拥有它,当使用函数别名的时候容易发生<code>丢失绑定对象</code></p>
<figure class="highlight js"><table><tr><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">foo</span>(<span class="params"></span>)</span>&#123;</span><br><span class="line">	<span class="built_in">console</span>.log(<span class="built_in">this</span>.a);</span><br><span class="line">&#125;</span><br><span class="line"><span class="keyword">var</span> obj = &#123;</span><br><span class="line">	a:<span class="number">2</span>,</span><br><span class="line">    foo:foo</span><br><span class="line">&#125;</span><br><span class="line"><span class="keyword">var</span> bar = obj.foo; <span class="comment">//使用了函数别名</span></span><br><span class="line"><span class="keyword">var</span> a = <span class="string">&quot;global&quot;</span>;</span><br><span class="line">bar(); <span class="comment">//&quot;global&quot;</span></span><br></pre></td></tr></table></figure>
<p><code>bar()</code>引用了<code>foo</code>函数本身，所以没有绑定对象，因此是一个默认对象，<code>丢失绑定对象</code>还会发生再传入回调函数的时候</p>
<figure class="highlight js"><table><tr><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">foo</span>(<span class="params"></span>)</span>&#123;</span><br><span class="line">    <span class="built_in">console</span>.log(a);</span><br><span class="line">&#125;</span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">doFoo</span>(<span class="params">fn</span>)</span>&#123;</span><br><span class="line">    fn();</span><br><span class="line">&#125;</span><br><span class="line"><span class="keyword">var</span> obj = &#123;</span><br><span class="line">	a:<span class="number">2</span>,</span><br><span class="line">    foo:foo</span><br><span class="line">&#125;</span><br><span class="line"><span class="keyword">var</span> a = <span class="string">&quot;global&quot;</span>;</span><br><span class="line">doFoo(obj.foo);</span><br></pre></td></tr></table></figure>
<p>常见的<code>setTimeout</code>其实是这样的</p>
<figure class="highlight js"><table><tr><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">setTimeout</span>(<span class="params">fn,delay</span>)</span>&#123;</span><br><span class="line">	<span class="comment">//wait delay</span></span><br><span class="line">    fn();</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>所以<code>setTimeout</code>会指向全局<code>window</code></p>
<h2 id="3-显式绑定"><a href="#3-显式绑定" class="headerlink" title="3. 显式绑定"></a>3. 显式绑定</h2><p>使用<code>call</code>和<code>aplly</code></p>
<figure class="highlight js"><table><tr><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">foo</span>(<span class="params"></span>)</span>&#123;</span><br><span class="line">	<span class="built_in">console</span>.log(<span class="built_in">this</span>.a)</span><br><span class="line">&#125;</span><br><span class="line"><span class="keyword">var</span> obj = &#123;</span><br><span class="line">    a:<span class="number">2</span></span><br><span class="line">&#125;</span><br><span class="line">foo.call(obj);<span class="comment">//2</span></span><br></pre></td></tr></table></figure>
<h3 id="1-硬绑定"><a href="#1-硬绑定" class="headerlink" title="1. 硬绑定"></a>1. 硬绑定</h3><figure class="highlight js"><table><tr><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">foo</span>(<span class="params"></span>)</span>&#123;</span><br><span class="line">	<span class="built_in">console</span>.log(<span class="built_in">this</span>.a);</span><br><span class="line">&#125;</span><br><span class="line"><span class="keyword">var</span> obj = &#123;</span><br><span class="line">    a:<span class="number">2</span></span><br><span class="line">&#125;</span><br><span class="line"><span class="keyword">var</span> bar = <span class="function"><span class="keyword">function</span>(<span class="params"></span>)</span>&#123;</span><br><span class="line">	foo.call(obj);</span><br><span class="line">&#125;</span><br><span class="line">bar();</span><br><span class="line"><span class="built_in">setTimeout</span>(bar,<span class="number">100</span>);</span><br><span class="line">bar.call(<span class="built_in">window</span>);</span><br></pre></td></tr></table></figure>
<p>创建了<code>bar</code>函数，函数<code>foo</code>的内部直接写死<code>call obj</code>对象，因此这是一种显式的强制绑定，称为硬绑定</p>
<p><code>硬绑定</code>常用的一个场景就是包裹函数</p>
<figure class="highlight js"><table><tr><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">foo</span>(<span class="params">something</span>)</span>&#123;</span><br><span class="line">    <span class="built_in">console</span>.log(<span class="built_in">this</span>.a,something);</span><br><span class="line">    <span class="keyword">return</span> <span class="built_in">this</span>.a + something;</span><br><span class="line">&#125;</span><br><span class="line"><span class="keyword">var</span> obj = &#123;</span><br><span class="line">    a:<span class="number">2</span>;</span><br><span class="line">&#125;</span><br><span class="line"><span class="keyword">var</span> bar = <span class="function"><span class="keyword">function</span>(<span class="params"></span>)</span>&#123;</span><br><span class="line">	<span class="keyword">return</span> foo.apply(obj,<span class="built_in">arguments</span>);</span><br><span class="line">&#125;;</span><br><span class="line"><span class="keyword">var</span> b = bar(<span class="number">3</span>); <span class="comment">//2 3</span></span><br><span class="line"><span class="built_in">console</span>.log(b); <span class="comment">//5</span></span><br></pre></td></tr></table></figure>
<p>相当于传进去的参数自动和<code>obj.a</code>做加法</p>
<p>另一种方法就是创建一个可以重复使用的辅助函数</p>
<figure class="highlight js"><table><tr><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">foo</span>(<span class="params">something</span>)</span>&#123;</span><br><span class="line">	<span class="built_in">console</span>.log(<span class="built_in">this</span>.a,something);</span><br><span class="line">    <span class="keyword">return</span> <span class="built_in">this</span>.a + something;</span><br><span class="line">&#125;</span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">bind</span>(<span class="params">fn,obj</span>)</span>&#123;</span><br><span class="line">	<span class="keyword">return</span> <span class="function"><span class="keyword">function</span>(<span class="params"></span>)</span>&#123;</span><br><span class="line">		<span class="keyword">return</span> fn.apply(obj,<span class="built_in">arguments</span>);</span><br><span class="line">    &#125;;</span><br><span class="line">&#125;</span><br><span class="line"><span class="keyword">var</span> obj = &#123;</span><br><span class="line">	a:<span class="number">2</span></span><br><span class="line">&#125;</span><br><span class="line"><span class="keyword">var</span> bar = bind(foo,obj);<span class="comment">//绑定需要的对象</span></span><br><span class="line"><span class="keyword">var</span> b = bar(<span class="number">3</span>) <span class="comment">//2 3</span></span><br><span class="line"><span class="built_in">console</span>.log(b); <span class="comment">//5</span></span><br></pre></td></tr></table></figure>
<p>这就是<code>bind</code>，返回一个新的函数，然后把<code>this</code>设置为上下文</p>
<figure class="highlight js"><table><tr><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">foo</span>(<span class="params">something</span>)</span>&#123;</span><br><span class="line">	<span class="built_in">console</span>.log(<span class="built_in">this</span>.a,something);</span><br><span class="line">    <span class="keyword">return</span> <span class="built_in">this</span>.a + something;</span><br><span class="line">&#125;</span><br><span class="line"><span class="keyword">var</span> obj = &#123;</span><br><span class="line">	a:<span class="number">2</span>;</span><br><span class="line">&#125;</span><br><span class="line"><span class="keyword">var</span> bar = foo.bind(obj);</span><br><span class="line"><span class="keyword">var</span> b = bar(<span class="number">3</span>); <span class="comment">//2 3</span></span><br><span class="line"><span class="built_in">console</span>.log(b); <span class="comment">//5</span></span><br></pre></td></tr></table></figure>


<h2 id="4-new绑定"><a href="#4-new绑定" class="headerlink" title="4.new绑定"></a>4.new绑定</h2><figure class="highlight js"><table><tr><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">foo</span>(<span class="params">a</span>)</span>&#123;</span><br><span class="line">	<span class="built_in">this</span>.a = a</span><br><span class="line">&#125;</span><br><span class="line"><span class="keyword">var</span> bar = <span class="keyword">new</span> foo(<span class="number">2</span>);</span><br><span class="line"><span class="built_in">console</span>.log(bar.a);</span><br></pre></td></tr></table></figure>
<p><code>new</code>的四步操作</p>
<ol>
<li>创建一个新的对象</li>
<li>新的对象进行<code>__proto__</code>连接</li>
<li>绑定<code>this</code>到新的创建的对象</li>
<li>如果没有返回别的对象，则返回<code>this</code>（新创建的对象）</li>
</ol>
<p><code>bar</code>是从<code>foo</code>中<code>new</code>出来的，所以这个<code>this.a</code>就是<code>bar.a</code>，等同于把<code>bar</code>新增了一个属性<code>a</code>,如果<code>this</code>指向的不是<code>bar</code>，那么会输出<code>undefined</code></p>
<h2 id="5-优先级"><a href="#5-优先级" class="headerlink" title="5.优先级"></a>5.优先级</h2><p>显式绑定✔和隐形绑定哪个优先级更高？</p>
<figure class="highlight js"><table><tr><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">foo</span>(<span class="params"></span>)</span>&#123;</span><br><span class="line">	<span class="built_in">console</span>.log(<span class="built_in">this</span>.a)</span><br><span class="line">&#125;</span><br><span class="line"><span class="keyword">var</span> obj1 = &#123;</span><br><span class="line">    a:<span class="number">2</span>,</span><br><span class="line">    foo:foo</span><br><span class="line">&#125;</span><br><span class="line"><span class="keyword">var</span> obj2 = &#123;</span><br><span class="line">    a:<span class="number">3</span>,</span><br><span class="line">    foo:foo</span><br><span class="line">&#125;</span><br><span class="line">obj1.foo(); <span class="comment">//2</span></span><br><span class="line">obj2.foo(); <span class="comment">//3</span></span><br><span class="line"></span><br><span class="line">obj1.foo.call(obj2); <span class="comment">//3</span></span><br><span class="line">obj2.foo.call(obj1); <span class="comment">//2</span></span><br></pre></td></tr></table></figure>
<p><strong>因为<code>obj1.foo.call(obj2);</code>输出是<code>3</code>,所以显示绑定的优先级更高</strong></p>
<p><code>new</code>绑定和隐式绑定的优先级谁高</p>
<figure class="highlight js"><table><tr><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">foo</span>(<span class="params">something</span>)</span>&#123;</span><br><span class="line">    <span class="built_in">this</span>.a = something</span><br><span class="line">&#125;</span><br><span class="line"><span class="keyword">var</span> obj1 = &#123;</span><br><span class="line">    foo:foo</span><br><span class="line">&#125;</span><br><span class="line"><span class="keyword">var</span> obj2 = &#123;&#125;;</span><br><span class="line"></span><br><span class="line">obj1.foo(<span class="number">2</span>);</span><br><span class="line"><span class="built_in">console</span>.log(obj1.a); <span class="comment">//2</span></span><br><span class="line"></span><br><span class="line">obj1.foo.call(obj2,<span class="number">3</span>);</span><br><span class="line"><span class="built_in">console</span>.log(obj2.a); <span class="comment">//3</span></span><br><span class="line"></span><br><span class="line"><span class="keyword">var</span> bar = <span class="keyword">new</span> obj1.foo(<span class="number">4</span>);</span><br><span class="line"><span class="built_in">console</span>.log(obj1.a); <span class="comment">//2</span></span><br><span class="line"><span class="built_in">console</span>.log(bar.a); <span class="comment">//4</span></span><br></pre></td></tr></table></figure>
<p><code>new</code>绑定比隐式绑定优先级高，而且<code>new</code>绑定比显式绑定优先级更高</p>
<h2 id="6-判断this"><a href="#6-判断this" class="headerlink" title="6. 判断this"></a>6. 判断this</h2><ol>
<li>函数是否在<code>new</code>中调用？<code>this</code>绑定的是新创建的对象</li>
</ol>
<figure class="highlight js"><table><tr><td class="code"><pre><span class="line"><span class="keyword">var</span> bar = <span class="keyword">new</span> foo();</span><br></pre></td></tr></table></figure>
<ol start="2">
<li>函数是否通过<code>call/apply</code>或者硬绑定调用？<code>this</code>绑定的是指向的对象</li>
</ol>
<figure class="highlight js"><table><tr><td class="code"><pre><span class="line"><span class="keyword">var</span> bar = foo.call(obj2)</span><br></pre></td></tr></table></figure>
<ol start="3">
<li>函数是否在某个上下文对象中调用？<code>this</code>绑定是上下文对象</li>
</ol>
<figure class="highlight js"><table><tr><td class="code"><pre><span class="line"><span class="keyword">var</span> bar = obj1.foo()</span><br></pre></td></tr></table></figure>
<ol start="4">
<li>默认绑定，如果是严格模式就是<code>undefined</code>,非严格模式下就绑定到<code>全局对象</code></li>
</ol>
<h3 id="6-绑定例外"><a href="#6-绑定例外" class="headerlink" title="6. 绑定例外"></a>6. 绑定例外</h3><h3 id="被忽略的this"><a href="#被忽略的this" class="headerlink" title="被忽略的this"></a>被忽略的<code>this</code></h3><p>如果把<code>null</code>或者<code>undefined</code>作为<code>this</code>的绑定对象传入<code>call</code>，<code>apply</code>或者<code>bind</code>，这些值会被忽略实际应用的是<code>默认绑定</code></p>
<figure class="highlight js"><table><tr><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">foo</span>(<span class="params"></span>)</span>&#123;</span><br><span class="line">	<span class="built_in">console</span>.log(<span class="built_in">this</span>.a);</span><br><span class="line">&#125;</span><br><span class="line"><span class="keyword">var</span> a = <span class="number">2</span>;</span><br><span class="line">foo.call(<span class="literal">null</span>); <span class="comment">//2</span></span><br></pre></td></tr></table></figure>
<p>在柯里化的时候可以运用<code>null</code></p>
<figure class="highlight js"><table><tr><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">foo</span>(<span class="params">a,b</span>)</span>&#123;</span><br><span class="line">	<span class="built_in">console</span>.log(<span class="string">&quot;a:&quot;</span> + a + <span class="string">&quot;, b:&quot;</span> + b);</span><br><span class="line">&#125;</span><br><span class="line"><span class="keyword">var</span> bar = foo.bind(<span class="literal">null</span>,<span class="number">2</span>);</span><br><span class="line">bar(<span class="number">3</span>); <span class="comment">//a:2 b:3</span></span><br></pre></td></tr></table></figure>
<p>如果函数并不关心<code>this</code>的话，但是依然需要传入一个占位，这时就可以用<code>null</code></p>
<h3 id="间接引用"><a href="#间接引用" class="headerlink" title="间接引用"></a>间接引用</h3><figure class="highlight js"><table><tr><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">foo</span>(<span class="params"></span>)</span>&#123;</span><br><span class="line">	<span class="built_in">console</span>.log(<span class="built_in">this</span>.a);</span><br><span class="line">&#125;</span><br><span class="line"><span class="keyword">var</span> a = <span class="number">2</span>;</span><br><span class="line"><span class="keyword">var</span> o = &#123;<span class="attr">a</span>:<span class="number">3</span>,<span class="attr">foo</span>:foo&#125;;</span><br><span class="line"><span class="keyword">var</span> p = &#123;<span class="attr">a</span>:<span class="number">4</span>&#125;;</span><br><span class="line"></span><br><span class="line">o.foo(); <span class="comment">//3</span></span><br><span class="line">(p.foo = o.foo)(); <span class="comment">//2</span></span><br></pre></td></tr></table></figure>
<p>因为<code>(p.foo = o.foo)();</code>的匿名函数<code>this</code>指向全局，所以返回的是全局的<code>a</code></p>
<h2 id="this词法-箭头函数作用域"><a href="#this词法-箭头函数作用域" class="headerlink" title="this词法(箭头函数作用域)"></a>this词法(箭头函数作用域)</h2><p>看看箭头函数的词法作用域</p>
<figure class="highlight js"><table><tr><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">foo</span>(<span class="params"></span>)</span>&#123;</span><br><span class="line">    <span class="keyword">return</span> <span class="function">(<span class="params">a</span>) =&gt;</span>&#123;</span><br><span class="line">        <span class="built_in">console</span>.log(<span class="built_in">this</span>.a)</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"><span class="keyword">var</span> obj1 = &#123;</span><br><span class="line">    a:<span class="number">2</span></span><br><span class="line">&#125;</span><br><span class="line"><span class="keyword">var</span> obj2 = &#123;</span><br><span class="line">    a:<span class="number">3</span></span><br><span class="line">&#125;</span><br><span class="line"><span class="keyword">var</span> bar = foo.call(obj1)</span><br><span class="line">bar.call(obj2) <span class="comment">//2</span></span><br></pre></td></tr></table></figure>
<p>箭头函数在调用时会捕获<code>foo()</code>的<code>this</code>,由于<code>foo()</code>的<code>this</code>绑定到<code>obj1</code>,而<strong>箭头函数的绑定无法修改</strong>,所以<code>bar</code>也绑定到<code>obj2</code></p>
<p>箭头函数最常用于回调函数,确保函数的<code>this</code>被绑定到指定对象</p>
<figure class="highlight js"><table><tr><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">foo</span>(<span class="params"></span>)</span>&#123;</span><br><span class="line">	<span class="built_in">setTimeout</span>(<span class="function">()=&gt;</span>&#123;</span><br><span class="line">        <span class="built_in">console</span>.log(<span class="built_in">this</span>.a)</span><br><span class="line">    &#125;,<span class="number">100</span>);</span><br><span class="line">&#125;</span><br><span class="line"><span class="keyword">var</span> obj = &#123;</span><br><span class="line">    a:<span class="number">2</span></span><br><span class="line">&#125;</span><br><span class="line">foo.call(obj) <span class="comment">//2</span></span><br></pre></td></tr></table></figure>


<h2 id="7-小结"><a href="#7-小结" class="headerlink" title="7.小结"></a>7.小结</h2><ol>
<li><p>函数是否在<code>new</code>中调用？<code>this</code>绑定的是新创建的对象</p>
</li>
<li><p>函数是否通过<code>call/apply</code>或者硬绑定调用？<code>this</code>绑定的是指向的对象</p>
</li>
<li><p>函数是否在某个上下文对象中调用？<code>this</code>绑定是上下文对象</p>
</li>
<li><p>默认绑定，如果是严格模式就是<code>undefined</code>,非严格模式下就绑定到<code>全局对象</code></p>
</li>
</ol>

    </div>

    
    
    

    <footer class="post-footer">
          <div class="post-tags">
              <a href="/tags/JS-U-dont-know-1/" rel="tag"># JS U dont know 1</a>
          </div>

        

          <div class="post-nav">
            <div class="post-nav-item">
                <a href="/2021/04/05/JS%20U%20DONT%20KNOW%201/%E7%AE%80%E5%8D%95%E8%AF%B4%E8%AF%B4this/" rel="prev" title="简单说说this">
                  <i class="fa fa-chevron-left"></i> 简单说说this
                </a>
            </div>
            <div class="post-nav-item">
                <a href="/2021/04/08/JS%20U%20DONT%20KNOW%201/null%E4%B8%8D%E6%98%AF%E5%AF%B9%E8%B1%A1/" rel="next" title="null不是对象">
                  null不是对象 <i class="fa fa-chevron-right"></i>
                </a>
            </div>
          </div>
    </footer>
  </article>
</div>







<script>
  window.addEventListener('tabs:register', () => {
    let { activeClass } = CONFIG.comments;
    if (CONFIG.comments.storage) {
      activeClass = localStorage.getItem('comments_active') || activeClass;
    }
    if (activeClass) {
      const activeTab = document.querySelector(`a[href="#comment-${activeClass}"]`);
      if (activeTab) {
        activeTab.click();
      }
    }
  });
  if (CONFIG.comments.storage) {
    window.addEventListener('tabs:click', event => {
      if (!event.target.matches('.tabs-comment .tab-content .tab-pane')) return;
      const commentClass = event.target.classList[1];
      localStorage.setItem('comments_active', commentClass);
    });
  }
</script>
</div>
  </main>

  <footer class="footer">
    <div class="footer-inner">


<div class="copyright">
  &copy; 
  <span itemprop="copyrightYear">2021</span>
  <span class="with-love">
    <i class="fa fa-heart"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">Lawted Wu</span>
</div>
<div class="busuanzi-count">
    <span class="post-meta-item" id="busuanzi_container_site_uv" style="display: none;">
      <span class="post-meta-item-icon">
        <i class="fa fa-user"></i>
      </span>
      <span class="site-uv" title="Total Visitors">
        <span id="busuanzi_value_site_uv"></span>
      </span>
    </span>
    <span class="post-meta-item" id="busuanzi_container_site_pv" style="display: none;">
      <span class="post-meta-item-icon">
        <i class="fa fa-eye"></i>
      </span>
      <span class="site-pv" title="Total Views">
        <span id="busuanzi_value_site_pv"></span>
      </span>
    </span>
</div>

    </div>
  </footer>

  


  <script src="https://cdn.jsdelivr.net/npm/darkmode-js@1.5.7/lib/darkmode-js.min.js"></script>
  <script src="https://cdn.jsdelivr.net/npm/animejs@3.2.1/lib/anime.min.js"></script>


<script>
var options = {
  bottom: '64px', // default: '32px'
  right: '32px', // default: '32px'
  left: 'unset', // default: 'unset'
  time: '0.5s', // default: '0.3s'
  mixColor: '#fff', // default: '#fff'
  backgroundColor: '#fff',  // default: '#fff'
  buttonColorDark: '#000',  // default: '#100f2c'
  buttonColorLight: '#fff', // default: '#fff'
  saveInCookies: true, // default: true,
  label: ' ', // default: ''
  autoMatchOsTheme: true // default: true
}
const darkmode = new Darkmode(options);
darkmode.showWidget();
</script><script src="/js/utils.js"></script><script src="/js/motion.js"></script><script src="/js/schemes/muse.js"></script><script src="/js/next-boot.js"></script>

  






  
  <script async src="https://busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script>





</body>
</html>
